//
//  LRUCache.cpp
//  CppDemo
//
//  Created by 蒋益杰 on 2017/5/20.
//  Copyright © 2017年 com.ed. All rights reserved.
//

#include "LRUCache.hpp"

using namespace std;

void LRUCache::set(int key, LRUData *data) {
    if (iteratorMap.find(key) != iteratorMap.end()) {
        //存在key，更新缓存
        auto iterator = iteratorMap[key];
        keyList.splice(keyList.begin(), keyList, iterator);
        iteratorMap[key] = keyList.begin();
        dataMap[key] = data;
    } else {
        if (keyList.size() == capacity) {
            int oldKey = keyList.back();
            iteratorMap.erase(oldKey);
            keyList.pop_back();
            //删除实际的大块数据
            dataMap.erase(oldKey);
        }
        //插入新key
        keyList.push_front(key);
        dataMap[key] = data;
        iteratorMap[key] = keyList.begin();
    }
}

LRUData *LRUCache::get(int key) {
    if (iteratorMap.find(key) != iteratorMap.end()) {
        //找到
        auto iterator = iteratorMap[key];
        keyList.splice(keyList.begin(), keyList, iterator);
        iteratorMap[key] = keyList.begin();
        return dataMap[key];
    } else {
        return nullptr;
    }
}

void LRUCache::print() {
    for (auto iterator = keyList.begin(); iterator != keyList.end(); iterator++){
        cout << "(" << *iterator << ", " << dataMap[*iterator]->str << "),";
    }
    cout << endl;
    
//    auto mapIter = iteratorMap.begin();
//    while (mapIter != iteratorMap.end()) {
//        cout << "key = " << (*mapIter).first << ", ";
//    }
//    cout << endl;
}

